var NonPurchaseWarehouseIn = function () {
  var UpdateForm = function () {
    var template = /* html */ `
      <div class="update-form">
        <div>
          <el-date-picker style="width:100%" v-model="inDayTime" size="small" value-format="timestamp" :editable="false"
            :clearable="false" placeholder="请选择入库日期"></el-date-picker>
        </div>
        <div style="text-align:center;margin-top:5px">
          <el-button type="primary" size="small" @click="update">修改</el-button>
        </div>
      </div>
    `;

    return {
      props: {
        warehouses: {
          type: Array,
          required: true
        }
      },

      data: function () {
        return {
          inDayTime: null
        };
      },

      methods: {
        update: function () {
          var inDayTime = this.inDayTime;
          if (inDayTime === null) {
            this.$alert('请选择入库日期', '信息');
            return;
          }
          var warehouses = this.warehouses;
          for (var i = 0; i < warehouses.length; i++) {
            var warehouse = warehouses[i];
            warehouse.inDay = inDayTime;
          }
          this.$emit('update-success');
        }
      },

      template: template
    };
  }();

  var template = /*html*/ `
    <div class="nonpurchase-warehousein" v-loading.fullscreen.lock="loading">
      <search-btn-view immediate btn-text="无采购入库查询" @before-open="resetSearch" @search="searchData" v-if="providerNameObj!==null">
        <template slot="append">
          <el-button type="primary" size="medium" @click="addMaterial">添加新物料</el-button>
          <el-button type="primary" size="medium" @click="save(false)">入库</el-button>
          <el-button type="primary" size="medium" @click="save(true)" :disabled="!selfApprovalPermission">审核过账</el-button>

          <template v-if="checkData.length>1">
            <el-popover v-model="openForm" title="修改入库日期" width="200" trigger="click" placement="bottom" style="margin-left:10px">
              <update-form v-if="openForm" :warehouses="checkData" @update-success="openForm=false"></update-form>
              <el-button slot="reference" type="primary" size="medium">修改入库日期</el-button>
            </el-popover>
          </template>
        </template>
        <div slot="search-content">
          <sys-common-search request-url="materialSelectFilter/getMaterialSelectData" :request-data="{type:4}" :search="search"
            :search-field="searchField" label-width="80px" input-width="220px">
            <template slot="append">
              <el-form-item label="单价">
                <el-input-number is-decimal-zero v-model="search.startPrice" placeholder="单价最小值" :controls="false" :min="0" :max="search.endPrice"
                  :precision="2" style="width:110px"></el-input-number>
                <span>-</span>
                <el-input-number is-decimal-zero v-model="search.endPrice" placeholder="单价最大值" :controls="false" :precision="2"
                  :min="search.startPrice?search.startPrice:0" style="width:110px"></el-input-number>
              </el-form-item>
            </template>
          </sys-common-search>
        </div>
      </search-btn-view>
      <div style="margin-bottom:5px" class="nonpurchase-warehousein-stat">
        <span>采购入库总数:{{totalPurchaseCount}}</span>
        <span>入库总金额:{{totalPurchaseMoney}}</span>
      </div>
      <div v-if="warehouseStatList.length>0" style="margin-bottom:5px" class="nonpurchase-warehousein-stat">
        <template v-for="item in warehouseStatList">
        <span :key="'materialType_'+item.materialType">{{item.materialType}}:{{item.count}}</span>
        </template>
      </div>

      <div class="nonpurchase-warehousein-table-div">
        <el-table fit stripe border :data="materialDataList" row-key="id" @selection-change="checkOrder" style="width:100%;" height="parent">
          <el-table-column v-if="isPayUser" sortable prop="materialType" key="materialType" label="物料类型" min-width="120px" header-align="center">
          </el-table-column>
          <el-table-column :resizable="false" key="providerName" label="供应商" min-width="160px" header-align="center">
            <template slot-scope="scope">
              <table-select style="width:152px" filterable v-model="scope.row.providerName" :options="providerNameList" @change="providerNameChange(scope.row)">
              </table-select>
            </template>
          </el-table-column>
          <el-table-column sortable prop="materialName" key="materialName" label="物料名称" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="color" key="color" label="编号" min-width="100px" header-align="center"></el-table-column>
          <el-table-column sortable prop="colorDescription" key="colorDescription" label="描述" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="model" key="model" label="规格" min-width="120px" header-align="center"></el-table-column>
          <el-table-column sortable prop="materialDeptName" key="materialDeptName" label="物料部门" min-width="110px" align="center"></el-table-column>
          <el-table-column sortable prop="providerNo" key="providerNo" label="供方编号" min-width="130px" header-align="center"></el-table-column>
          <el-table-column sortable prop="unitPrice" key="unitPrice" label="物料单价" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable prop="unit" key="unit" label="物料单位" min-width="100px" align="center"></el-table-column>
          <el-table-column sortable prop="count" key="count" label="库存" min-width="100px" align="center"></el-table-column>
          <el-table-column :resizable="false" key="inCount" label="入库数" width="120px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero :controls="false" v-model="scope.row.inCount" :min="0" :max="999999999.9999" :precision="SysUtil.getMaterialNumberPrecision(scope.row.unit,4)"
                style="width:112px" size="mini" @change="inCountChange(scope.row)"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" prop="unitPrice" key="unitPrice" label="结算单价" width="100px" header-align="center">
            <template slot-scope="scope">
              <el-input-number v-if="canUpdateUnitAndPrice" :controls="false" v-model="scope.row.inCountPrice" :min="0"
                :max="999999999.9999" :precision="4" style="width:92px" size="mini" @change="unitPriceChange(scope.row)"></el-input-number>
              <span v-else>{{scope.row.inCountPrice}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="结算单位" key="inCountUnit" width="100px" header-align="center">
            <template slot-scope="scope">
              <table-select clearable filterable style="width:92px" v-model="scope.row.inCountUnit" :options="unitList">
              </table-select>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="结算数量" key="sumMoneyCount" width="100px" header-align="center">
            <template slot-scope="scope">
              <el-input-number is-decimal-zero :controls="false" v-model="scope.row.sumMoneyCount" :min="0" :max="999999999.9999" @change="unitPriceChange(scope.row)"
                :precision="SysUtil.getMaterialNumberPrecision(scope.row.inCountUnit,4)" style="width:92px" size="mini"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="金额" width="140px" header-align="center">
            <template slot-scope="scope">
              <el-input-number v-if="canUpdateUnitAndPrice" :controls="false" v-model="scope.row.inOutMoney" :min="0"
                :precision="2" style="width:130px" size="mini" @change="totalMoneyChange(scope.row)"></el-input-number>
              <span v-else>{{scope.row.inOutMoney}}</span>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="是否含税" key="isTax" width="140px" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isTax" size="mini" style="width:130px">
                <el-option :value="1" label="不含税"></el-option>
                <el-option :value="2" label="含税"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="仓位" width="110px" key="positions" header-align="center">
            <template slot-scope="scope">
              <sys-autocomplete open-all-dropdown :key="scope.row._dataId" size="mini" v-model="scope.row.positions" style="width:100px" :options="scope.row.positionList">
              </sys-autocomplete>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="入库日期" width="135px" key="inDay" header-align="center">
            <template slot-scope="scope">
              <el-date-picker style="width:125px" v-model="scope.row.inDay" size="mini" value-format="timestamp" :editable="false"
                :clearable="false"></el-date-picker>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" label="备注" width="130px" key="remark" header-align="center">
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.remark" style="width:120px"></el-input>
            </template>
          </el-table-column>
          <el-table-column :resizable="false" type="selection" width="40px" align="center" key="selection" fixed="right"></el-table-column>
        </el-table>
      </div>
      <table-pagination v-if="pagination.totalCount!==0" :pagination="pagination" @change="pageChange"></table-pagination>

      <el-dialog title="添加物料" :visible.sync="isShowCopmanyMaterialAddForm" top="5vh">
        <div style="height: calc(80vh - 54px); overflow: auto">
          <company-material-form v-if="isShowCopmanyMaterialAddForm" :company-material="addCompanyMaterial" @add="addCompanyMaterialAfter"
            :dropdown-option="dropdownOption">
          </company-material-form>
        </div>
      </el-dialog>
    </div>
  `;
  return {
    mixins: [
      tablePaginationMixin()
    ],
    props: {
      unitList: {
        type: Array,
        required: true
      }
    },
    computed: {
      totalPurchaseMoney: function () {
        var checkData = this.checkData;
        var totalMoney = _.sumBy(checkData, function (warehouse) {
          var inOutMoney = warehouse.inOutMoney;
          if (inOutMoney === undefined) {
            inOutMoney = 0;
          }
          return inOutMoney;
        });
        totalMoney = _.round(totalMoney, 2);
        return totalMoney;
      },
      totalPurchaseCount: function () {
        var checkData = this.checkData;
        var totalCount = _.sumBy(checkData, function (warehouse) {
          var inCount = warehouse.inCount;
          if (inCount === undefined) {
            inCount = 0;
          }
          return inCount;
        });
        totalCount = _.round(totalCount, 4);
        return totalCount;
      },
      warehouseStatList: function () {
        var warehouseList = this.checkData;
        var warehouseGroup = _.groupBy(warehouseList, function(obj){
          var materialType = obj.materialType;
          if (SysUtil.isEmpty(materialType)) {
            return '无';
          }
          return materialType;
        });
        var statList = [];
        for (var materialType in warehouseGroup) {
          var list = warehouseGroup[materialType];
          var totalCount = _.sumBy(list, function (obj) {
            var inCount = obj.inCount;
            if (SysUtil.isEmpty(inCount)) {
              return 0;
            }
            return inCount;
          });
          statList.push({
            materialType: materialType,
            count: totalCount
          });
        }
        return statList;
      }
    },
    data: function () {
      var search = {
        materialName: '',
        materialType: '',
        model: '',
        color: '',
        providerName: '',
        materialDept: '',
        providerNo: '',
        startPrice: undefined,
        endPrice: undefined
      };
      return {
        loading: false,
        isPayUser: false,
        moment: moment,
        selfApprovalPermission: false,
        materialDataList: [],
        checkData: [],
        providerNameList: [],
        dropdownOption: {},
        addCompanyMaterial: new CompanyMaterialTable(),
        isShowCopmanyMaterialAddForm: false,
        unitList: [],
        canUpdateUnitAndPrice: true,
        search: _.cloneDeep(search),
        oldSearch: _.cloneDeep(search),
        searchField: ['materialName', 'materialType', 'model', 'color', 'providerName', 'providerNo', 'materialDept'],
        openForm: false,
        providerNameObj: null
      };
    },
    created: function () {
      this.loading = true;
      var self = this;
      Promise.all([
        this.checkPayUser(),
        this.checkApprovalPermission(),
        this.setProviderNameList()
      ]).then(function () {
        self.loading = false;
      }).catch(function () {
        self.loading = false;
      });
    },
    methods: {
      checkPayUser: function () {
        var self = this;
        return SysUtil.getUser().then(function (user) {
          var isPayUser = user.companyInfo.status === 1;
          self.isPayUser = isPayUser;
          return isPayUser;
        });
      },

      checkApprovalPermission: function () {
        var self = this;
        return PermissionUtil.ajaxCheckPermission(6).then(function (hasApproval) {
          self.selfApprovalPermission = hasApproval;
          return hasApproval;
        });
      },

      setProviderNameList: function () {
        var self = this;
        ajaxRequest('basicData/getCustomerName', {
          view: 1
        }).then(function (providerList) {
          var providerNameObj = {};
          var providerNameList = [];
          for (var i = 0; i < providerList.length; i++) {
            var provider = providerList[i];
            var isTax = provider.isTax;
            if (isTax === 0) {
              isTax = 2;
            }
            var customerName = provider.customerName;
            providerNameObj[customerName] = isTax;
            providerNameList.push(customerName);
          }
          self.providerNameObj = providerNameObj;

          providerNameList = _.uniq(providerNameList);
          self.providerNameList = providerNameList;
          return providerNameList;
        });
      },

      resetSearch: function () {
        this.search = _.cloneDeep(this.oldSearch);
      },

      searchData: function () {
        this.setMaterialDataList(true);
      },

      pageChange: function () {
        this.setMaterialDataList();
      },

      setMaterialDataList: function (isSearch) {
        if (!isSearch) {
          this.search = _.cloneDeep(this.oldSearch);
        } else {
          this.pagination.currentPage = 1;
        }
        var search = this.search;
        var pagination = this.pagination;
        var currentPage = pagination.currentPage;
        var pageSize = pagination.pageSize;
        var start = (currentPage - 1) * pageSize;
        var postData = {
          start: start,
          length: pageSize
        }
        var fields = ['materialName', 'materialType', 'model', 'color', 'providerName', 'providerNo', 'startPrice', 'endPrice'];
        SysUtil.setPostData(postData, search, fields);

        var materialDept = search.materialDept;
        if (materialDept !== '') {
          postData.materialDeptId = materialDept.materialDeptId;
        }

        this.loading = true;
        var self = this;
        ajaxRequest("companyMaterial/getVagueCompanyMaterialByMapToPage", postData, false).then(function (res) {
          if (isSearch) {
            self.oldSearch = _.cloneDeep(self.search);
          }
          var dataList = res.returnData;
          var unitList = self.unitList;
          var providerNameObj = self.providerNameObj;
          for (var i = 0; i < dataList.length; i++) {
            var data = dataList[i];
            self.changeDetailData(data);
            PurchaseWarehouseInUnit.setInCountUnit(data, unitList);
            SysUtil.tableSetDeptData(data);

            var positionList = data.positionList;
            var positions = '';
            if (!SysUtil.isEmpty(positionList)) {
              positions = positionList[0];
            }
            data.positions = positions;

            var providerName = data.providerName;
            var isTax = providerNameObj[providerName];
            if (isTax === undefined) {
              isTax = '';
            }
            data.isTax = isTax;
          }
          self.canUpdateUnitAndPrice = res.code === 1;
          self.materialDataList = dataList;
          self.pagination.totalCount = res.iTotalRecords;
          self.loading = false;
        }).catch(function () {
          self.loading = false;
        });
      },
      addMaterial: function () {
        this.addCompanyMaterial = new CompanyMaterialTable();
        this.isShowCopmanyMaterialAddForm = true;
      },

      addCompanyMaterialAfter: function (data) {
        this.isShowCopmanyMaterialAddForm = false;
        var idArray = [data.id];
        var self = this;
        self.loading = true;
        ajaxRequest("companyMaterial/getCheckMaterialTable", {
          "idArray": JSON.stringify(idArray)
        }).then(function (res) {
          self.loading = false;
          var materialData = res[0];
          self.changeDetailData(materialData);
          PurchaseWarehouseInUnit.setInCountUnit(materialData, self.unitList);
          self.materialDataList.push(materialData);
        }).catch(function () {
          self.loading = false;
        });
      },
      //入库
      save: function (isAduit) {
        var postData = [];
        var checkData = this.checkData;
        if (checkData.length === 0) {
          this.$alert('请选择需要入库的物料', '信息');
          return;
        }
        //循环勾选物料
        var fields = ['materialCode', 'materialName', 'color', 'providerName', 'model', 'positions', 'remark',
          'sumMoneyCount', 'inCountUnit', 'inCountPrice', 'inOutMoney', 'isTax'
        ];
        for (var i = 0; i < checkData.length; i++) {
          var data = checkData[i];
          if (data.inCount === undefined) {
            this.$alert('请输入入库数量', '信息');
            return;
          } else if (data.inCount === 0) {
            this.$alert('入库数量不能为0', '信息');
            return;
          }

          if (data.inCountPrice === undefined) {
            this.$alert('请输入结算单价', '信息');
            return;
          }

          if (data.inCountUnit === '') {
            this.$alert('请输入结算单位', '信息');
            return;
          }

          if (data.sumMoneyCount === undefined) {
            this.$alert('请输入结算数量', '信息');
            return;
          } else if (data.sumMoneyCount === 0) {
            this.$alert('结算数量不能为0', '信息');
            return;
          }

          if (data.inOutMoney === undefined) {
            this.$alert('请输入金额', '信息');
            return;
          }

          var obj = {
            type: 4,
            warehouseType: 4,
            count: data.inCount
          };
          SysUtil.setPostData(obj, data, fields, false, true);
          var inDay = data.inDay;
          if (typeof inDay === 'number') {
            obj.inDay = moment(inDay).format('YYYY-MM-DD');
          } else {
            obj.inDay = '';
          }
          postData.push(obj);
        }
        this.loading = true;
        var self = this;
        ajaxRequest("warehouse/saveWarehouseInNotPurchaseOrder", {
          array: JSON.stringify(postData),
          isAduit: isAduit
        }).then(function (res) {
          self.$alert(res, '信息');
          self.loading = false;
          self.setMaterialDataList(true);
        }).catch(function () {
          self.loading = false;
        });
      },
      checkOrder: function (selection) {
        this.checkData = selection;
      },
      changeDetailData: function (data) {
        data.remark = '';
        data.inCountPrice = data.unitPrice;
        data.positoins = '';
        data.inOutMoney = 0;
        var inDay = moment().valueOf();
        if (SysUtil.isEmpty(inDay)) {
          inDay = (new Date).getTime();
        }
        data.inDay = inDay;
      },

      inCountChange: function (materialData) {
        var inCount = materialData.inCount;
        materialData.sumMoneyCount = inCount;
        this.unitPriceChange(materialData);
      },

      unitPriceChange: function (warehouse) {
        var count = warehouse.sumMoneyCount;
        if (count === 0 || count === undefined) {
          count = warehouse.inCount;
        }
        var unitPrice = warehouse.inCountPrice;
        var totalMoney = SysUtil.calPrice(count, unitPrice, 'total');
        warehouse.inOutMoney = totalMoney;
      },

      totalMoneyChange: function (warehouse) {
        var count = warehouse.sumMoneyCount;
        if (count === 0 || count === undefined) {
          count = warehouse.inCount;
        }
        var totalMoney = warehouse.inOutMoney;
        var unitPrice = SysUtil.calPrice(count, totalMoney, 'unit', 4);
        warehouse.inCountPrice = unitPrice;
      },

      providerNameChange: function (purchase) {
        var providerName = purchase.providerName;
        var providerNameObj = this.providerNameObj;
        var isTax = providerNameObj[providerName];
        if (isTax === undefined) {
          isTax = 2;
        }
        purchase.isTax = isTax;
      }
    },
    components: {
      SearchBtnView: SearchBtnView,
      SysCommonSearch: SysCommonSearch,
      CompanyMaterialForm: CompanyMaterialForm,
      CustomerForm: CustomerForm,
      SysAutocomplete: SysAutocomplete,
      TableSelect: TableSelect,
      UpdateForm: UpdateForm
    },
    template: template
  }
}();
